import Foundation
import CommonCrypto

extension Data {
    // 将 Data 转换为 HEX 字符串
    var toHexString: String {
        return self.map { String(format: "%02hhx", $0) }.joined()
    }

    // 将 HEX 字符串转换为 Data
    init?(fromHexString hexString: String) {
        let length = hexString.count
        guard length % 2 == 0 else { return nil }

        var data = Data(capacity: length / 2)
        var index = hexString.startIndex
        for _ in 0..<length/2 {
            let byteString = hexString[index..<hexString.index(index, offsetBy: 2)]
            if var byte = UInt8(byteString, radix: 16) {
                data.append(&byte, count: 1)
            } else {
                return nil
            }
            index = hexString.index(index, offsetBy: 2)
        }
        self = data
    }
}

func encryptDecryptText(inputText: String, shouldEncrypt: Bool) -> String? {
    // 密码和偏移量定义在方法内部
    let encryptionKey = "00112233445566778899aabbccddeeff" // 16 bytes key (hex)
    let initializationVector = "000102030405060708090a0b0c0d0e0f"  // 16 bytes IV (hex)

    guard let keyData = Data(fromHexString: encryptionKey),
          let ivData = Data(fromHexString: initializationVector),
          let inputData = inputText.data(using: .utf8) else {
        return nil
    }

    let keyLength = size_t(kCCKeySizeAES128)
    let ivLength = size_t(kCCBlockSizeAES128)
    var numberOfBytesProcessed: size_t = 0

    // 计算加密或解密后的数据大小
    let processedDataSize = inputData.count + kCCBlockSizeAES128
    var processedData = Data(count: processedDataSize)

    let operation = shouldEncrypt ? kCCEncrypt : kCCDecrypt

    // 使用 withUnsafeMutableBytes 方法避免直接在同一块内修改
    let status = processedData.withUnsafeMutableBytes { processedBytes in
        inputData.withUnsafeBytes { dataBytes in
            keyData.withUnsafeBytes { keyBytes in
                ivData.withUnsafeBytes { ivBytes in
                    CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding),
                            keyBytes.baseAddress, keyLength,
                            ivBytes.baseAddress,
                            dataBytes.baseAddress, inputData.count,
                            processedBytes.baseAddress, processedDataSize,
                            &numberOfBytesProcessed)
                }
            }
        }
    }

    guard status == kCCSuccess else {
        return nil
    }

    processedData.removeSubrange(numberOfBytesProcessed..<processedData.count)

    if shouldEncrypt {
        return processedData.base64EncodedString()
    } else {
        // 解密时需要将 Base64 编码的字符串解码回 Data 对象
        guard let data = Data(base64Encoded: inputText) else {
            return nil
        }
        return String(data: data, encoding: .utf8)
    }
}

